//
//  WWUserAccountViewModel.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/3/24.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit

class WWUserAccountViewModel: NSObject {

    //MARK: WWUserAccount视图模型////视图模型需要引用  模型对象  --> 视图模型需要处理数据逻辑
    var userAccount : WWUserAccount?
    
    //MARK: 单例
    static let shared : WWUserAccountViewModel = WWUserAccountViewModel()
    
    //在已经登陆的情况下给模型赋值,//保证以后再判断是否登录的时候 不在访问磁盘
    //在持久化的磁盘中读取模型赋值给userAccount
    override init() {
        super .init()
        userAccount = self.loadUserInfo()
        
    }
    //计算型属性,判断用户是否登陆,accessToken不为nil同时令牌没有过期
    var userLogin : Bool{
        if userAccount?.access_token != nil && isExpired == false{
            return true
        }
        //默认没有登陆
        return false
    }
    //过期时间的比较,过期时间比当前日期大就没有过期, 过期时间和当前日期比较  降序
    var isExpired : Bool{
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            return false
        }
        //默认过期
        return true
    }
    
    //获取用户Token
    open func loadAccessToken (code:String,finished:@escaping (Bool)->()){
        let urlStirng = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : app_key,
                          "client_secret" : app_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : app_callBack]
        WWNetworkTools.shared.request(method: .POST, urlString: urlStirng, parameters: parameters) { (responseObject, error) in
            if error != nil {
                finished(false)
                return
            }
            //请求用户信息
            self.loadUserInfo(dict: responseObject as! [String : Any], loadInfoFinished: finished)
        }
    }
    
    
    //请求用户信息
    private func loadUserInfo (dict : [String : Any],loadInfoFinished:@escaping (Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token" : token,
                          "uid" : uid]
        WWNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                loadInfoFinished(false)
                return
            }
            //转换类型
            var userInfoDict = responseObject as! [String : Any]
            //合并字典
            for (key,value) in dict {
                userInfoDict[key] = value
            }
            //字典转模型
            let userAccount = WWUserAccount(dict: userInfoDict)
            
            //归档用户信息
            self.saveUserInfo(userAcconut: userAccount)
            //给单例对象的模型属性赋值
            self.userAccount = userAccount
            //执行成功的回调
            loadInfoFinished(true)
        }
    }
    
    
    //归档用户信息
    private func saveUserInfo (userAcconut:WWUserAccount){
        NSKeyedArchiver.archiveRootObject(userAcconut, toFile: path as String)
    }
    
    //读取磁盘
    open func loadUserInfo () -> WWUserAccount?{
        //调用解档的方法
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path as String)
        if let userAccount = account as? WWUserAccount {
            return userAccount
        }
        return nil
    }
}
